import { computed, nextTick, reactive, watch, shallowRef, toRefs, ref } from "vue"
import NP from "number-precision"

export function getRandomNum(min, max, excluded) {
  const numbers = []
  for (let i = min; i <= max; i++) {
    if (i !== excluded) {
      numbers.push(i)
    }
  }
  return numbers[Math.floor(Math.random() * numbers.length)]
}

const formatTime = (time) => {
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
    .toString()
    .padStart(2, "0")
  return `${minutes}:${seconds}`
}

export function useAudioPlayer(options) {
  const { source = "", autoplay = false } = options || {}
  const audioRef = shallowRef(null)
  const state = reactive({
    // 是否播放
    isPlaying: autoplay,
    speed: 1,
    // 静音，值为0时不静音，值为1-100时为静音时存储的静音前的音量
    muteVolume: 0,
    // 音量
    volume: 100,
    // 当前时间(秒)
    currentSecond: 0,
    // 持续时间(总时间.秒)
    durationSecond: 0,
    // 播放进度百分比
    progressRatio: 0,
  })

  // 设置音量
  watch(
    () => state.volume,
    (newVolume) => {
      if (!audioRef.value) return
      console.log(newVolume, "---newVolume")

      audioRef.value.volume = NP.divide(newVolume, 100)
    },
    { immediate: true }
  )

  // 当前时间(分钟)
  const currentMinute = computed(() => formatTime(state.currentSecond))
  // 持续时间(总时间.分钟)
  const durationMinute = computed(() => formatTime(state.durationSecond))

  // 当前播放源
  const audioSource = ref(source)

  const updateSource = (newSource) => {
    state.isPlaying = false
    audioSource.value = newSource
  }

  // 切换播放状态，启动/暂停
  const togglePlayStatus = () => {
    if (!audioRef.value) return

    state.isPlaying ? audioRef.value.pause() : audioRef.value.play()

    state.isPlaying = !state.isPlaying
  }
  // 播放时间更新事件
  const onTimeupdate = (e) => {
    state.currentSecond = e.target.currentTime
    updateProgressRatioHandle()
  }
  // 元数据加载完成事件
  const onLoadedmetadata = (e) => {
    state.durationSecond = e.target.duration
  }
  // 播放结束事件
  const onEnded = () => {
    // const eventMap = {
    //   loop: playNextAudio,
    //   single: playAudio,
    //   random: playNextAudio,
    // }
    // const event = eventMap[state.loopType]
    // event ? event() : stopAudio()
  }

  // 设置进度
  const setPlayProgress = (value) => {
    if (!audioRef.value) return
    state.currentSecond = value
    audioRef.value.currentTime = state.currentSecond
    playAudio()
  }

  // 播放
  const playAudio = () => {
    if (!audioRef.value) return
    audioRef.value.play()
    state.isPlaying = true
  }
  // 暂停
  const pauseAudio = () => {
    if (!audioRef.value) return
    audioRef.value.pause()
    state.isPlaying = false
  }
  // 停止
  const stopAudio = () => {
    if (!audioRef.value) return
    audioRef.value.pause()
    audioRef.value.currentTime = 0
    state.isPlaying = false
  }

  // 选择播放
  const selectPlayAudio = async (index) => {
    state.currentPlayIndex = index
    await nextTick()
    playAudio()
  }

  // 更新播放进度百分比
  const updateProgressRatioHandle = () => {
    const t = (state.currentSecond / state.durationSecond) * 100
    state.progressRatio = parseFloat(t.toFixed(2))
  }

  // 切换静音状态
  const toggleMuteStatus = () => {
    if (state.volume) {
      state.muteVolume = state.volume
      state.volume = 0
    } else {
      state.volume = state.muteVolume || 100
      state.muteVolume = 0
    }
  }
  // 设置音量
  const setVolume = (value, type) => {
    const isMinus = type === "minus" ? true : false
    if (isMinus) {
      const realVal = state.volume - value
      state.volume = realVal <= 0 ? 0 : realVal
    } else {
      const realVal = state.volume + value
      state.volume = realVal >= 100 ? 100 : realVal
    }
  }
  // 设置播放速率
  const setSpeed = (value) => {
    if (!audioRef.value) return
    state.speed = value
    audioRef.value.playbackRate = value
  }

  // onMounted(() => {})

  return {
    audioRef,
    ...toRefs(state),
    audioSource,
    updateSource,
    currentMinute,
    durationMinute,
    setPlayProgress,
    togglePlayStatus,
    toggleMuteStatus,
    setVolume,
    playAudio,
    pauseAudio,
    stopAudio,
    selectPlayAudio,
    onLoadedmetadata,
    onTimeupdate,
    onEnded,
    setSpeed,
  }
}
